import Axios from 'axios'
import { Notification } from 'element-ui'
import Qs from 'qs'
import { URL } from '@/config'
Axios.defaults.timeout = 5000;
// Axios.defaults.baseURL = 'http://www.payjiehai.com'
// Axios.defaults.baseURL = 'http://localhost:3333';
Axios.defaults.baseURL = URL;


const http = ({ url, data = {}, method = 'post' }) => {
    const m = method.toLowerCase()
    const config = {
        method: m,
        url,
        headers: {
            'Content-Type': 'application/json'
        }
    }
    const token = sessionStorage.getItem('token')
    if (token) {
        config.headers['Authorization'] = 'Token ' + token
    }
    if (m === 'get' || m === 'delete') {
        config.params = data
    } else {
        config.data = data
    }

    return new Promise((resolve, reject) => {
        Axios(config)
            .then(res => {
                if (res.status === 200) {
                    resolve(res.data)
                } else {
                    Notification({
                        title: '提示',
                        message: res.data.error_msg || '出错了',
                        type: 'error'
                    });
                    reject()
                }
            })
            .catch(err => {
                Notification({
                    title: '提示',
                    message: '网络错误',
                    type: 'error'
                });
            })
    })
}

export default http
